<?php
/**
 * Created by PhpStorm.
 * User: xcx
 * Date: 2017/6/2
 * Time: 10:17
 */

class Controller_Adminmall_Order extends Controller_Adminmall_Abstract
{

    private $DB_SERVER = "xhs_slave";
    private $DB_SERVER_MASTER = "xhs_master";

    /*
     * 未处理小红薯订单列表
     */
    public function listAction(){
//        $this->openDebug();
        global $_F;
        $uid = FRequest::getInt("uid");
        $mobile = FRequest::getString('mobile');
        $nickname = FRequest::getString("nickname");
        $o_id = FRequest::getString("o_id");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');
        $page = FRequest::getInt("page");
        $status = FRequest::getInt("status");

        $where = array();

        if ($start_time < 1) {
            $start_time = date('Y-m-d', strtotime("-6 days"));
        }
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $where['o.create_time']['gte'] = $start_time.' 00:00:00';
        $where['o.create_time']['lte'] = $end_time.' 23:59:59';

        if($uid){
            $where['o.uid'] = $uid;
        }

        if($mobile){
            $where['o.phone'] = array("like" => "%{$mobile}%");
        }

        if($nickname){
            $where['u.username'] = array("like" => "%{$nickname}%");
        }

        if($_F['gid'] != 1){
            $where['o.shop_id'] = $_F['member']['shop_id'];
        }


        if($status){
            $where['o.status'] = $status;
        }

        if($o_id){
            $where['o.o_id'] = $o_id;
        }


        $table = new FTable('orders', 'o', $this->DB_SERVER);
        $list = $table->fields("o.*, u.username, u.cell_phone, cs.name as shop_name")
            ->leftJoin('user', 'u', 'u.uid=o.uid')
//            ->leftJoin("orders_product", "op", "op.o_id=o.o_id")
            ->leftJoin("chain_shop", "cs", "cs.id=o.shop_id")
            ->where($where)
            ->order("auto_id desc")
            ->limit(20)
            ->page($page)
            ->select();
        $pagerInfo = $table->getPagerInfo();
        $this->assign('page_info', $pagerInfo);

        if ($list) {
            $productTable = new FTable("orders_product", "", $this->DB_SERVER);
            foreach ($list as &$item) {
                if ($item['o_id']) {
                    $ret = $productTable->where("o_id={$item['o_id']}")->select();
                    $item['products'] = $ret;
                }
            }
        }
//        var_dump($list);
        $this->assign("data", $list);
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);
        $this->display('order/order-list');
    }


    /*
     * 已处理小红薯订单列表
     */
    public function listDAction(){
//        $this->openDebug();
        $mobile = FRequest::getString('mobile');
        $nickname = FRequest::getString("nickname");
        $source = FRequest::getString("source");
        $o_id = FRequest::getString("o_id");
        $intention = FRequest::getString("intention");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');
        $page = FRequest::getInt("page");
        $c_uid = FRequest::getInt("c_uid");
        $s_uid = FRequest::getInt("s_uid");

        $where = array();

        if ($start_time < 1) {
            $start_time = date('Y-m-d', strtotime("-6 days"));
        }
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $where['create_time']['gte'] = $start_time.' 00:00:00';
        $where['create_time']['lte'] = $end_time.' 23:59:59';

        if($mobile){
            $where['mobile'] = $mobile;
        }
        if($nickname){
            $where['nickname'] = array('like' => "%{$nickname}%");
        }
        if($source){
            $where['source'] =$source;
        }
        if($intention){
            $where['join_intention'] =$intention;
        }
        if($s_uid){
            $where['s_uid'] = $s_uid;
        }
        if($c_uid){
            $where['c_uid'] = $c_uid;
        }
        if($o_id){
            $where['o_id'] = $o_id;
        }

        $where["uo.status"] = array("eq" => 2);


        $table = new FTable('orders', 'uo', '');
        $list = $table->fields("uo.*, p.name as pro, c.name as cit")
            ->leftJoin("privince", "p", "uo.province=p.code")
            ->leftJoin("city", "c", "c.code=uo.city")
            ->where($where)
            ->order("id desc")
            ->limit(20)
            ->page($page)
            ->select();
        $pagerInfo = $table->getPagerInfo();
        $this->assign('page_info', $pagerInfo);

//        var_dump($list);
        $this->assign("data", $list);
        $this->display('order/order-list');
    }

    public function listDelAction(){
//        $this->openDebug();
        $mobile = FRequest::getString('mobile');
        $nickname = FRequest::getString("nickname");
        $source = FRequest::getString("source");
        $intention = FRequest::getString("intention");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');
        $page = FRequest::getInt("page");
        $c_uid = FRequest::getInt("c_uid");
        $s_uid = FRequest::getInt("s_uid");

        $where = array();

        /*if ($start_time < 1) {
            $start_time = date('Y-m-d', time());
        }
        if ($end_time < 1) {
            $end_time = date('Y-m-d', time());
        }
        $where['create_time']['gte'] = $start_time.' 00:00:00';
        $where['create_time']['lte'] = $end_time.' 23:59:59';*/

        if($mobile){
            $where['mobile'] = $mobile;
        }
        if($nickname){
            $where['nickname'] = array('like' => "%{$nickname}%");
        }
        if($source){
            $where['source'] =$source;
        }
        if($intention){
            $where['join_intention'] =$intention;
        }
        if($s_uid){
            $where['s_uid'] = $s_uid;
        }
        if($c_uid){
            $where['c_uid'] = $c_uid;
        }

        $where["uo.status"] = array("eq" => 3);


        $table = new FTable('orders', 'uo', '');
        $list = $table->fields("uo.*, p.name as pro, c.name as cit")
            ->leftJoin("privince", "p", "uo.province=p.code")
            ->leftJoin("city", "c", "c.code=uo.city")
            ->where($where)
            ->order("id desc")
            ->limit(20)
            ->page($page)
            ->select();
        $pagerInfo = $table->getPagerInfo();
        $this->assign('page_info', $pagerInfo);

//        var_dump($list);
        $this->assign("data", $list);
        $this->display('order/order-list-del');
    }

    /*
     * 订单处理
     */
    public function orderModifyAction(){
        global $_F;
        $this->openDebug();
        $id = FRequest::getInt("id");
        if($this->isPost()){
            $id = FRequest::getPostInt('id');
            $shop_id = FRequest::getPostInt('shop_id');
            $remark = FRequest::getPostString("remark") ? FRequest::getPostString("remark") : "";
            $contact = FRequest::getPostString("contact") ? FRequest::getPostString("contact") : "";
            $phone = FRequest::getPostString("phone") ? FRequest::getPostString("phone") : "";
            $address = FRequest::getPostString("address") ? FRequest::getPostString("address") : "";
            $status = FRequest::getPostInt("status");



            $save = array();
            if($shop_id){
                $save['shop_id'] = $shop_id;
            }
            if($remark){
                $save['remark'] = $remark;
            }
            if($contact){
                $save['contact'] = $contact;
            }
            if($phone){
                $save['phone'] = $phone;
            }
            if($address){
                $save['address'] = $address;
            }
            if($status){
                $save['status'] = $status;
            }

            $table =  new FTable("orders", "", 'xhs_master');
            $table->update1($save, array("auto_id" => $id));
            $this->success("修改成功", $_F['refer']);
        }else{
            $table =  new FTable("orders", "", $this->DB_SERVER);
            $data = $table->fields("*")->where(array("auto_id" => $id))->find();
            $this->assign("data", $data);
        }

        $chainTable = new FTable("chain_shop", "", $this->DB_SERVER);
        $chainData = $chainTable->where("status=1")->select();
        $this->assign("chainData", $chainData);
        $userStatus = FConfig::get("type.userStatus");
        $this->assign("userStatus", $userStatus);
        $this->display("order/modify");
    }

    /*
     * 报表导出功能
     */
    public function excelDaoAction(){
        $this->openDebug();
        global $_F;
        $uid = FRequest::getInt("uid");
        $mobile = FRequest::getString('mobile');
        $nickname = FRequest::getString("nickname");
        $o_id = FRequest::getString("o_id");
        $start_time = FRequest::getString("begin_date");
        $end_time = FRequest::getString('end_date');
        $page = FRequest::getInt("page");
        $status = FRequest::getInt("status");

        $where = array();

        if ($start_time) {
            $where['o.create_time']['gte'] = $start_time.' 00:00:00';
        }
        if ($end_time) {
            $where['o.create_time']['lte'] = $end_time.' 23:59:59';
        }



        if($uid){
            $where['o.uid'] = $uid;
        }

        if($mobile){
            $where['o.phone'] = array("like" => "%{$mobile}%");
        }

        if($nickname){
            $where['u.username'] = array("like" => "%{$nickname}%");
        }

        if($_F['gid'] != 1){
            $where['o.shop_id'] = $_F['member']['shop_id'];
        }


        if($status){
            $where['o.status'] = $status;
        }

        if($o_id){
            $where['o.o_id'] = $o_id;
        }


        $table = new FTable('orders', 'o', $this->DB_SERVER);
        $list = $table->fields("o.*, u.username, u.cell_phone, cs.name as shop_name")
            ->leftJoin('user', 'u', 'u.uid=o.uid')
//            ->leftJoin("orders_product", "op", "op.o_id=o.o_id")
            ->leftJoin("chain_shop", "cs", "cs.id=o.shop_id")
            ->where($where)
            ->order("auto_id desc")
            ->select();

        $productTable = new FTable("orders_product", "", $this->DB_SERVER);
        if ($list) {
            foreach ($list as &$item) {
                if ($item['o_id']) {
                    $whereP['o_id'] = $item['o_id'];
                    $ret = $productTable->where($whereP)->select();
                    $item['products'] = $ret;
                }else{
                    $item['products'] = "";
                }
            }
        }

//        FResponse::output($list);exit();
        self::teAction($list, $start_time, $end_time);
        exit();

    }

    public static function teAction($data, $start_time, $end_time){

        $name="{$start_time}至{$end_time}订单导出";
        require_once APP_ROOT . "/flib/PHPExcel/PHPExcel.php";
        $objPHPExcel = new PHPExcel();
        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("juxin")
            ->setLastModifiedBy("juxin")
            ->setTitle("Simple")
            ->setSubject("Simple")
            ->setDescription("Simple")
            ->setKeywords("excel")
            ->setCategory("result file");
        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/


//商品名	商品数量	商品规格/口味	商品单价（卖出价）	商品总金额（卖出价）

        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '订单号')
            ->setCellValue('B1', '用户id')
            ->setCellValue('C1', '昵称')

            ->setCellValue('D1', '商品名')
            ->setCellValue('E1', '商品数量')
            ->setCellValue('F1', '商品规格/口味')
            ->setCellValue('G1', '商品单价')
            ->setCellValue('H1', '商品总金额')

            ->setCellValue('I1', '订单支付配送费')
            ->setCellValue('J1', '订单总金额')
            ->setCellValue('K1', '配送店')
            ->setCellValue('L1', '收货人')
            ->setCellValue('M1', '联系方式')
            ->setCellValue('N1', '所在区')
            ->setCellValue('O1', '地址')
            ->setCellValue('P1', '下单时间')
            ->setCellValue('Q1', '状态')
            ->setCellValue('R1', '配送距离km');

        //E 列为文本
        $objPHPExcel->getActiveSheet()->getStyle('A')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);



        $num = 1;
//        FResponse::output($data);exit();
        foreach($data as $k => $v){

            /*if($v['o_id'] == '2017091213362051992'){
                FResponse::output($v);
                exit();
            }*/

            $num=$num+1;
            $row_start = $num;

            if ($v['status'] == 1) {   //1待付款，2待接单，3商家已接单，4派送中, 5已完成, 6已取消',
                $status_z = "待付款";
            } elseif ($v['status'] == 2) {
                $status_z = "待接单";
            } elseif ($v['status'] == 3) {
                $status_z = "商家已接单";
            } elseif ($v['status'] == 4) {
                $status_z = "派送中";
            } elseif ($v['status'] == 5) {
                $status_z = "已完成";
            } elseif ($v['status'] == 6) {
                $status_z = "已取消";
            }else{
                $status_z = "";
            }


            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，uid是你查出数组的键值，下面以此类推
                ->setCellValue('A'.$num, html_entity_decode(" ".$v['o_id']))
                ->setCellValue('B'.$num, $v['uid'])
                ->setCellValue('C'.$num, htmlentities($v['username'])) //iconv("UTF-8", "GBK", $v['username']);
//                ->setCellValue('D'.$num, $v['username'])
//                ->setCellValue('E'.$num, $v['username'])
//                ->setCellValue('F'.$num, $v['username'])
//                ->setCellValue('G'.$num, $v['username'])
//                ->setCellValue('H'.$num, $v['shop_name'])
                ->setCellValue('I'.$num, $v['send_price'])
                ->setCellValue('J'.$num, $v['pay_price'])
                ->setCellValue('K'.$num, html_entity_decode($v['shop_name']))
                ->setCellValue('L'.$num, html_entity_decode($v['contact']))
                ->setCellValue('M'.$num, html_entity_decode($v['phone']))
                ->setCellValue('N'.$num, html_entity_decode($v['county']))
                ->setCellValue('O'.$num, html_entity_decode($v['address']))
                ->setCellValue('P'.$num, $v['create_time'])
                ->setCellValue('Q'.$num, $status_z)
                ->setCellValue('R'.$num, $v['dis']);


            foreach($v['products'] as $key => $value){
                $tmp = json_decode($value['spec_list']);
                $new="";
                foreach($tmp as $key1 => $value1) {
                    $new = json_decode($value1);
                }

                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('D'.$num, ' '.$value['title'])   //iconv("UTF-8", "GBK", $value['title']);
                    ->setCellValue('E'.$num, $value['paynum'])
                    ->setCellValue('F'.$num, $new->value)
                    ->setCellValue('G'.$num, $value['price_new'])
                    ->setCellValue('H'.$num, $value['price_new']*$value['paynum']);




                if($key != count($v['products'])-1){
                    $num=$num+1;
                }
            }

            //合并单元格
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("A{$row_start}:A{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("B{$row_start}:B{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("C{$row_start}:C{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("I{$row_start}:I{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("J{$row_start}:J{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("K{$row_start}:K{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("L{$row_start}:L{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("M{$row_start}:M{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("N{$row_start}:N{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("O{$row_start}:O{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("P{$row_start}:P{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("Q{$row_start}:Q{$num}");
            $objPHPExcel->setActiveSheetIndex(0)->mergeCells("R{$row_start}:R{$num}");




            }


            /*$num=24;
            $val1 = $objPHPExcel->getActiveSheet()->getCell('D'.$num)->getValue();//这个就是获取每个单元格的值
            var_dump($val1);
            echo "<br>";
            exit();*/

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('22');
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('12');
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('20');
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth('18');
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth('12');
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth('12');
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth('14');
        $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth('30');
        $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth('17');

        //所有单元格居中
//        $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//        $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        //单个单元格居中
//        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        $objPHPExcel->getActiveSheet()->setTitle('orders');
        $objPHPExcel->setActiveSheetIndex(0);

        // 输出
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');



        exit;
    }

    public function delAction(){
        global $_F;
        $flag = FRequest::getInt("flag") ? FRequest::getInt("flag") : 0;
        $id = FRequest::getInt("id");
        if ($id) {
            FDB::remove("user_order", array("id" => $id), true);
            $this->success("删除成功!", $_F['refer']);
        } else {
            $this->success("删除失败，id为空！", $_F['refer']);
        }
    }

    public function modifyStatusAction(){
        global $_F;
//        $this->openDebug();
        $flag = FRequest::getInt("flag") ? FRequest::getInt("flag") : 0;
        $id = FRequest::getInt("id");
        $status = FRequest::getInt("status");
        if ($id) {
            $table = new FTable("orders", "", 'xhs_master');
            $logTable = new FTable("orders_log", "", 'xhs_master');
            $ret = $table->where("auto_id={$id}")->find();
            $save = array(
                "status" => $status,
                "operate_id" => $_F['uid'],
                "order_id" => $ret['o_id'],
            );
//            $table->update1(array('status' => $status), array("auto_id" => $id));
            Service_Order::updateExpend($status, $id);
            $logTable->insert($save);
            $this->success("操作成功!", $_F['refer']);
        } else {
            $this->success("操作失败，id为空！", $_F['refer']);
        }
    }


    public function orderDealAction(){
        global $_F;
        $id = FRequest::getInt("id");
        if($this->isPost()){
            $remarks = FRequest::getPostString("remarks") ? FRequest::getPostString("remarks") : "";
            $o_id = FRequest::getPostString("o_id") ? FRequest::getPostString("o_id") : "";
            $status = FRequest::getPostInt('status');
            $id = FRequest::getPostInt("id");

            $save = array();
            if($remarks){
                $save['remarks'] = $remarks;
            }
            if($o_id){
                $save['order_id'] = $o_id;
            }
            $save['operate_id'] = $_F['uid'];
            $save['status'] = $status;
            $table = new FTable("orders", "", 'xhs_master');
            $logTable = new FTable("orders_log", "", 'xhs_master');
            $table->update1(array('status' => $status), array("auto_id" => $id));
            $logTable->insert($save);
            $this->success("修改222成功", $_F['refer']);
        }else{
            $table = new FTable("orders", "", $this->DB_SERVER);
            $data = $table->where("auto_id={$id}")->find();
            $this->assign("data", $data);
        }
        $this->display("order/modify-order");
    }

    public function tipsAction(){
//        $this->openDebug();
        global $_F;
        $shop_id = $_F['shop_id'];
        $result = Service_Order::orderPopQueue($shop_id);
        if($result['size'] >= 1){
            FResponse::output(array('status'=>1,'msg'=>'收到新的订单啦','num'=>$result['size']));
        }else{
            FResponse::output(array('status'=>0));
        }
    }

    public function changePriceAction(){
        $o_id = FRequest::getString('o_id');
        if($o_id){
            $table = new FTable('orders','','xhs_master');
            $table->where(array('o_id'=>$o_id))->update1(array('pay_price'=>0.01));
        }
    }

    public function printOrderAction(){
        $o_id = FRequest::getString('o_id');
        $table = new FTable('orders','','xhs_master');
        $order = $table->where(array('o_id'=>$o_id))->find();
        echo json_encode($order);
    }

    /**
     * 取消配送
     */
    public function cancelDistributionAction(){
        global $_F;
        $id = FRequest::getInt("id");
        if($id){
            $result = Service_Order::cancelOrder($id);
            if($result['respcd'] == "0000"){
                $table = new FTable('orders','','xhs_master');
                $ret = $table->where(array('auto_id'=>$id))->update1(array('ship_status'=>7));
                if($ret){
                    $this->success("取消配送成功", $_F['refer']);
                }else{
                    $this->error("取消配送失败",$_F['refer']);
                }
            }else{
                $this->error($result['respmsg'], $_F['refer']);
            }
        }else{
            $this->error("id为空",$_F['refer']);
        }
    }

    /**
     * 通用配置
     */
    public function PeizhiAction(){
        global $_F;
        if($this->isPost()){
            $id = FRequest::getPostInt('id');
            $price_send = FRequest::getPostFloat('price_send');
            $table = new FTable('peizhi', '',$this->DB_SERVER_MASTER);
            $data = array('price_send' => $price_send);
            $ret = $table->where(array('id' => $id))->save($data);
            if($ret){
                Service_Order::clearPeizhiCache();
                $this->success('修改成功', $_F['refer']);
            }else{
                $this->error('修改失败', $_F['refer']);
            }
        }

        $id = FRequest::getInt('id');
        if($id){
            $table = new FTable('peizhi', '',$this->DB_SERVER);
            $data = $table->where("id={$id}")->find();
            $this->assign('data', $data);
        }

        $this->display('order/peizhi');
    }

}